package com.xianyu.open.restclient.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 *
 * @author bailinan
 * @date 2018/7/21
 */
public class SingletonFactoryBean {
    private final static Map<String, Object> BEAN_CACHE = new ConcurrentHashMap<>(16);

    /**
     * 单例工厂
     * @param beanName
     * @param supplier
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getObject(String beanName, Supplier<T> supplier){
        if (BEAN_CACHE.get(beanName) == null){
            synchronized (BEAN_CACHE){
                if (BEAN_CACHE.get(beanName) == null){
                    Object object = supplier.get();
                    BEAN_CACHE.put(beanName, object);
                }
            }
        }
        return (T) BEAN_CACHE.get(beanName);
    }
}
